package com.ewzj.bigdata.mvp.presenter

import android.Manifest
import android.app.Activity
import android.app.Application
import android.text.TextUtils
import android.util.Log
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.ewzj.bigdata.SplashActivity
import com.ewzj.bigdata.app.config.AppKey
import com.ewzj.bigdata.app.config.AppLocationListener
import com.ewzj.bigdata.app.extensions.DelegatesExt
import com.ewzj.bigdata.app.extensions.startIntent
import com.ewzj.bigdata.app.utils.Apputils
import com.ewzj.bigdata.app.utils.RxUtils
import com.ewzj.bigdata.mvp.contract.LogoContract
import com.ewzj.bigdata.mvp.model.rspbean.*
import com.ewzj.bigdata.mvp.ui.activity.MainTabActivity
import com.ewzj.bigdata.mvp.ui.fragment.HomeFragment
import com.google.gson.Gson
import com.jess.arms.mvp.BasePresenter
import com.jess.arms.utils.DataHelper
import com.jess.arms.utils.DeviceUtils
import com.jess.arms.utils.UiUtils
import com.tbruyelle.rxpermissions2.RxPermissions
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import me.jessyan.rxerrorhandler.core.RxErrorHandler
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber
import timber.log.Timber
import java.util.concurrent.TimeUnit
import javax.inject.Inject

/**
 * author:zhangjing
 * 作用:
 * return:
 */
class LogoPresenter @Inject constructor(val mGson: Gson, val mErrorHandler: RxErrorHandler, val application: Application, view: LogoContract.View, model: LogoContract.Model) : BasePresenter<LogoContract.Model, LogoContract.View>(model, view) {
    val isFirst: Boolean by DelegatesExt.preference(application, AppKey.IS_FIRST, true)
    val mLocationClient: LocationClient by lazy { LocationClient(application) }
    var savedcity: String by DelegatesExt.preference(application, AppKey.LOCATION_CITY, "")
    val context = mRootView as Activity
    fun configInfo(): Unit {
//        配置信息
        mModel.getconfigInfo().compose(RxUtils.applySchedulers(mRootView))
                .subscribe(object : ErrorHandleSubscriber<BaseData<ConfigBean>>(mErrorHandler) {
                    override fun onNext(t: BaseData<ConfigBean>) {
                        var config = t.data!!
                        AppKey.mappConfig.content = config.content
                        AppKey.mappConfig.download_url = config.download_url
                        AppKey.mappConfig.qq = config.qq
                        AppKey.mappConfig.version_code = config.version_code
                        AppKey.mappConfig.wechat = config.wechat
                        AppKey.mappConfig.weibo = config.weibo
                        AppKey.mappConfig.port=config.port
                    }

                })
    }


    fun updateInfo(): Unit {
//        升级信息
    }

    fun saveCity(): Unit {
    }

    fun lanuchActivity(): Unit {
        Observable.just(isFirst).delay(2, TimeUnit.SECONDS).subscribe(object : ErrorHandleSubscriber<Boolean>(mErrorHandler) {
            override fun onNext(t: Boolean) {
                if (t) {
                    val activity: RxAppCompatActivity = mRootView as RxAppCompatActivity
                    activity.startIntent(SplashActivity::class.java as Class<Any>)
                    activity.finish()
                } else {
                    goMainActivity()
                }
            }

        })

    }

    fun goMainActivity() {
        if (mRootView!=null){
            val activity: RxAppCompatActivity = mRootView as RxAppCompatActivity
            activity.startIntent(MainTabActivity::class.java as Class<Any>)
            activity.finish()
        }
    }

    fun getAdList() {
        mModel.getAdList().compose(RxUtils.applySchedulers(mRootView))
                .subscribe({
                    rsp ->
                    Observable.just(isFirst).delay(2, TimeUnit.SECONDS).compose(RxUtils.applySchedulers(mRootView))
                            .subscribe(Consumer { t:Boolean ->kotlin.run{
                                if (t) {
                                    val activity: RxAppCompatActivity = mRootView as RxAppCompatActivity
                                    activity.startIntent(SplashActivity::class.java as Class<Any>)
                                    activity.finish()
                                } else {
                                    if (rsp.data!!.list != null && rsp.data!!.list.size > 0) {
                                        mRootView.setLogoview(rsp.data!!)
                                        Observable.interval(0, 1, TimeUnit.SECONDS)
                                                .doAfterTerminate {
                                                    goMainActivity()
                                                }
                                                .compose(RxUtils.applySchedulers(mRootView))
                                                .subscribe(object : ErrorHandleSubscriber<Long>(mErrorHandler) {
                                                    override fun onNext(t: Long) {
                                                        if (t!! >= 5) {
                                                            goMainActivity()
                                                        }
                                                        mRootView.settvTimeview(t!!)
                                                    }
                                                })
                                    } else {
                                        goMainActivity()
                                    }

                                }
                            }  }, Consumer { e ->  goMainActivity() })
                }, { goMainActivity() })

    }

    fun initBdLocation() {
        Apputils.Utils.initLocation(mLocationClient)
        mLocationClient.registerLocationListener(AppKey.locationListener)
        AppKey.locationListener.locationlistener = object : AppLocationListener.LoctionListener {
            override fun locationComplete(location: BDLocation) {
                AppKey.bdLocation = location
                if (location == null) {
                    if (DeviceUtils.hasInternet(context)){
                        getAdList()
                    }else{
                        lanuchActivity()
                    }
                    var citybean = CityBean.ListEntity()
                    citybean.setLat(30.576279)
                    citybean.setLon(104.071216)
                    AppKey.bdLocation!!.latitude = 30.576279
                    AppKey.bdLocation!!.longitude = 104.071216
                    citybean.setCity("成都市")
                    citybean.setLocatecity("定位失败")
                    citybean.setId("63")
                    savedcity = mGson.toJson(citybean)
                    return
                }
                if (TextUtils.isEmpty(location.city)) {
                    if (savedcity.isNullOrEmpty()){
                        var citybean = CityBean.ListEntity()
                        citybean.setLat(30.576279)
                        citybean.setLon(104.071216)
                        AppKey.bdLocation!!.latitude = 30.576279
                        AppKey.bdLocation!!.longitude = 104.071216
                        citybean.setCity("成都市")
                        citybean.setLocatecity("定位失败")
                        citybean.setId("63")
                        savedcity = mGson.toJson(citybean)
                        lanuchActivity()
                        return
                    }else{
                        goMainActivity()
                        return
                    }

                }

//                    第一次进入还没有保存上一次的城市信息
                    mModel.getCityByname(location.city).compose(RxUtils.applySchedulers(mRootView))
                            .subscribe({
                                t: BaseData<CitySearchBean> ->kotlin.run {
                                if (savedcity.isNullOrEmpty()) {
                                    if (t.data!!.getList().size == 0) {
                                        run {
                                            val listEntity = CityBean.ListEntity()
                                            listEntity.setCity("成都市")
                                            listEntity.setId("63")
                                            listEntity.setFirst("c")
                                            listEntity.setLocatecity(location.city)
                                            listEntity.setLat(location.latitude)
                                            listEntity.setLon(location.longitude)
                                            savedcity = mGson.toJson(listEntity)
                                        }
                                    } else {
                                        val listEntity = t!!.data!!.list[0]
                                        val cityBean = CityBean.ListEntity()
                                        cityBean.city = listEntity.getCity()
                                        cityBean.id = listEntity.getId()
                                        cityBean.locatecity = location.city
                                        cityBean.adress = location.address.city + "  " + location.address.district
                                        cityBean.district = location.district
                                        cityBean.lat = location.latitude
                                        cityBean.lon = location.longitude
                                        savedcity = mGson.toJson(cityBean)
                                    }
                                }else{
                                    var citybean=mGson.fromJson(savedcity,CityBean.ListEntity::class.java)
                                    citybean.locatecity=location.city
                                    savedcity=mGson.toJson(citybean)
                                }
                                getAdList()
                            }
                            },{  e: Throwable? -> run{
                                val listEntity = CityBean.ListEntity()
                                listEntity.setCity("成都市")
                                listEntity.setId("63")
                                listEntity.setFirst("c")
                                listEntity.setLocatecity(location.city)
                                listEntity.setLat(location.latitude)
                                listEntity.setLon(location.longitude)
                                savedcity = mGson.toJson(listEntity)
                                goMainActivity()
                            }
                            })

            }
        }
        RxPermissions(context).request(Manifest.permission.ACCESS_FINE_LOCATION)
                .subscribe(Consumer { t ->
                    if (t) {
                        if (AppKey.bdLocation == null) {
                            mLocationClient.start()
                        }

                    } else {
                        var citybean = CityBean.ListEntity()
                        citybean.setLat(30.576279)
                        citybean.setLon(104.071216)
                        citybean.setCity("成都市")
                        citybean.setLocatecity("定位失败")
                        citybean.setId("63")
                        savedcity = mGson.toJson(citybean)
                        UiUtils.SnackbarText("你已拒绝定位")
                        if (DeviceUtils.hasInternet(context)){
                            getAdList()
                        }else{
                            lanuchActivity()
                        }

                    }
                })


    }

    override fun onDestroy() {
        mLocationClient.stop()
        super.onDestroy()
    }
}